#include "TcpConnection.h"

using namespace std;
using namespace std::placeholders;
TcpConnection::TcpConnection(io_service& sio, const std::string& ip, int port) :
	m_Socket(sio),
	m_EndPoint(ip::address::from_string(ip), port)
{
}

TcpConnection::~TcpConnection()
{
	m_Socket.close();
}

void TcpConnection::Connect()
{
	m_Socket.async_connect(m_EndPoint, std::bind(&TcpConnection::OnConnect, this, ::_1));
}

void TcpConnection::OnConnect(system::error_code ec)
{
	if (!ec)
	{
		fmt::print("[OnConnect] success\n");
		m_IsConnected = true;

		DoRecvRsp();
		AddRequest("I am connected");
	}
}

std::string TcpConnection::GetResponse()
{
	if (m_RspQue.empty())
		return {};

	auto msg = m_RspQue.front();

	m_RspQue.pop();

	return msg;
}

void TcpConnection::AddRequest(const std::string& contents)
{
	m_Socket.async_send(asio::buffer(contents.c_str(), contents.length()), std::bind(&TcpConnection::OnWrite, this, ::_1, ::_2));
}

void TcpConnection::OnRead(error_code ec, std::size_t length)
{
	if (!ec)
	{
		fmt::print("[OnRead]: error_code = {}\n {}\n", ec.value(), m_ReadBuf);

		m_RspQue.emplace(m_ReadBuf);

		/*static int index = 1;
		AddRequest(fmt::format("This is number {} request", index++));*/
	}
	DoRecvRsp();
}

void TcpConnection::OnWrite(error_code ec, std::size_t length)
{
	fmt::print("[OnWriet] : error_code = {}, length = {}\n", ec.value(), length);

	DoRecvRsp();
}

void TcpConnection::DoRecvRsp()
{
	m_Socket.async_read_some(
		asio::buffer(m_ReadBuf),
		std::bind(&TcpConnection::OnRead, this, ::_1, ::_2)
	);
}